package ueditor;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UploaderServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private String[] byteSuffixs = new String[] { ".jpg", ".png", ".gif",
			".swf", ".psd", ".bmp", ".rar" };

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String contextPath = request.getContextPath();
		String servletPath = request.getServletPath();
		String requestURI = request.getRequestURI();
		if (contextPath == null) { // root context
			contextPath = "";
		}
		String filePath = requestURI.substring(contextPath.length()
				+ servletPath.length());
		filePath = Uploader.getUploadPath(request) +"upload/"+ filePath;

		// 二进制资源
		for (String byteSuffix : byteSuffixs) {
			if (filePath.endsWith(byteSuffix)) {
				InputStream in = new FileInputStream(filePath);
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int n = 0;
				while (-1 != (n = in.read(buffer))) {
					output.write(buffer, 0, n);
				}
				byte[] bytes = output.toByteArray();
				if (bytes != null) {
					response.getOutputStream().write(bytes);
					return;
				}
			}
		}
		// 文本资源
		InputStreamReader reader = new InputStreamReader(new FileInputStream(
				filePath));
		StringWriter writer = new StringWriter();
		char[] buffer = new char[1024];
		int n = 0;
		while(-1 != (n = reader.read(buffer))) {
			writer.write(buffer,0,n);
		}
		String text = writer.toString();
		if (text != null) {
			response.getWriter().write(text);
			return;
		}
	}

}
